package com.tjw.ec.common.core.exception;

import com.baomidou.mybatisplus.extension.api.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 异常处理器
 * 
 * @author t-junwen
 * @email t-junwen@foxmail.com
 * @date 2018年10月27日 下午10:16:19
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
	private Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 处理自定义异常
	 */
	@ExceptionHandler(BusinessException.class)
	public R handleBusinessException(BusinessException e){
		R r = new R();
		r.setCode(e.getCode());
		r.setMsg(e.getMsg());
		return r;
	}

	/**
	 * 处理自定义异常
	 */
	@ExceptionHandler(ServiceException.class)
	public R handleServiceException(ServiceException e){
		R r = new R();
		r.setCode(e.getCode());
		r.setMsg(e.getMsg());
		return r;
	}

	@ExceptionHandler(DuplicateKeyException.class)
	public R handleDuplicateKeyException(DuplicateKeyException e){
		logger.error(e.getMessage(), e);
		return R.failed("数据库中已存在该记录");
	}

	@ExceptionHandler(Exception.class)
	public R handleException(Exception e){
		logger.error(e.getMessage(), e);
		return R.failed(e.getMessage());
	}
}
